package jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;

public class JacksonTest {

    public static void main(String[] args) throws Exception {
        //1.创建Student对象
        Student student = new Student("张三", 19);

        //2. 获取jackson的操作对象
        ObjectMapper mapper = new ObjectMapper();
        //3. 将Student对象转为String
        String s = mapper.writeValueAsString(student);
        //4. 将user对象写入文件中
        mapper.writeValue(new File("day14-code/src/json/student.json"), student);
        //5. 将user对象写入字节数组
        byte[] bytes = mapper.writeValueAsBytes(student);
        System.out.println(new String(bytes));
        // 6. 将json字符串：str 转为Student
        Student s1 = mapper.readValue(s, Student.class);
        System.out.println("将json字符串：str 转为Student" + s1);
        //7. 将json文件中的json字符串读入程序中并转为User
        Student s2 = mapper.readValue(new File("day14-code/src/json/student.json"), Student.class);
        System.out.println("将json文件中的json字符串读入程序中并转为User" + s2);
        // 8. 将字节数组bytes中的内容转化为User
        Student s3 = mapper.readValue(bytes, Student.class);
        System.out.println("将字节数组bytes中的内容转化为User" + s3);

    }
}

class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "姓名；" + name + "，年龄：" + age;
    }
}